package ca.cbc.msb.util;

import java.io.IOException;
import java.util.Calendar;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FTPUtil {
	private static Logger logger = LoggerFactory.getLogger(FTPUtil.class);
    private final static String SYNDICATION_BASE_URL = AppConfig.getProperty("syndication.base.url");
    private final static String SYNDICATION_USERNAME = AppConfig.getProperty("syndication.username");
    private final static String SYNDICATION_PASSWORD = AppConfig.getProperty("syndication.password");
    private final static String HOST_NAME;
    private final static String FILE_NAME_PREFIX;


    static {
    	String[] tmpStrArray = SYNDICATION_BASE_URL.split("//")[1].split("/", 2);
    	HOST_NAME = tmpStrArray[0];
    	FILE_NAME_PREFIX = tmpStrArray[1];
    }

    private static FTPClient getClient() throws IOException {
        FTPClient client = new FTPClient();
        client.connect(HOST_NAME);
        client.login(SYNDICATION_USERNAME, SYNDICATION_PASSWORD);
        return client;

    }

    public static void deleteFile(String fileName) {   
    	fileName = FILE_NAME_PREFIX + fileName;
    	FTPClient client = null;
    	try {
            client = getClient();
    		if(client.deleteFile(fileName))
    			logger.info("file {} delete from ftp", fileName);
    		else
    			logger.error("file {} failed delete from ftp", fileName);
    		client.logout();
    	} catch (IOException e) {
    		logger.error("file {} failed delete from ftp", fileName, e);
    	} finally {
    		try {
    			if(client != null)
    				client.disconnect();
    		} catch (IOException e) {
    			logger.error("closing ftp client error", e);
    		}
    	}  	
    }

    public static boolean isFile(String fileName){
        try {
            String file = getClient().getModificationTime(fileName);
            logger.info("Status of {} is {}.",fileName,file == null ? "*NOT IN FTP*" : "*IN FTP*");
            return file != null;
        } catch (IOException e) {
            logger.error("Could not connect to akamai netstorage FTP account.",e);
            return false;
        }
    }
    
    public static void deleteOldFiles() {
        FTPClient client = null;
        Calendar today = Calendar.getInstance();
        today.add(Calendar.DATE, -14);

        try{
            client = getClient();
            FTPFile[] files = client.listFiles();
            for (FTPFile file : files){
                if(file.getTimestamp().before(today)){
                    logger.info("@@@---@@@ Deleting the file {}", file.getName());
                   client.deleteFile(file.getName());
                }

            }
        } catch (IOException e) {
            logger.error("Exception in cleaning the old files", e);
        }  finally {
            if(client != null){
                try {
                    client.disconnect();
                } catch (IOException e) {
                    logger.error("Error closing the ftp connection");
                }
            }
        }
    }
}
